package com.yksj.healthtalk.ui.home;

import java.util.ArrayList;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import org.handmark.pulltorefresh.library.PullToRefreshListView;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.yksj.healthtalk.adapter.SearchAdapter;
import com.yksj.healthtalk.adapter.SearchAdapter.onClickSalonAttentionListener;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.db.ChatUserHelper;
import com.yksj.healthtalk.entity.GroupInfoEntity;
import com.yksj.healthtalk.entity.MessageEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.chatting.ChatActivity;
import com.yksj.healthtalk.ui.salon.SalonInformationActivity;
import com.yksj.healthtalk.ui.salon.SalonReadSelf;
import com.yksj.healthtalk.ui.salon.SalonSelectPaymentOptionActivity.OnBuyTicketHandlerListener;
import com.yksj.healthtalk.utils.SalonHttpUtil;
import com.yksj.healthtalk.utils.ToastUtil;
/**
 * 我的沙龙搜索列表
 * @author jack_tang
 *
 */
public class MySalonSearchActivity extends BaseFragmentActivity implements
OnClickListener, OnItemClickListener, OnBuyTicketHandlerListener,OnRefreshListener2<ListView>, onClickSalonAttentionListener {
	
	private GroupInfoEntity mGroupInfoEntity;
	private PullToRefreshListView pullRefreshView;
	private ListView mListView;
	@SuppressWarnings("rawtypes")
	private SearchAdapter mSalonAdapter;
	private ArrayList<GroupInfoEntity> entities;
	private String Flag = "";
	private String flagPlacing="-100000";

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			 if(action.equals(MessagePushService.ACTION_COLLECT_GROUP)){
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(MySalonSearchActivity.this, R.string.groupNewFail);
				} else {
					SalonHttpUtil.requestAttentionToSalonResult(MySalonSearchActivity.this,cacheGroupInfoEntity, mAppData, chatUserHelper);
					mSalonAdapter.notifyDataSetChanged();
				}
			
			}else if (action.equals(MessagePushService.ACTION_COLLECT_GROUP_NOT)) {
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(MySalonSearchActivity.this, R.string.groupNewFail);
				} else {
					SalonHttpUtil.requestUnfollowToSalonResult(MySalonSearchActivity.this,cacheGroupInfoEntity, mAppData, chatUserHelper);
					mSalonAdapter.notifyDataSetChanged();
				}
			}else if(action.equals(MessagePushService.ACTION_REPEAT_STATE)){
				if ("y".equalsIgnoreCase(intent.getStringExtra("FLAG"))) {
					ToastUtil.showShort(getApplicationContext(), "转发成功");
					// 好友转发消息需要保存到本地
					requestHttpSendStatus();
				} else {
					ToastUtil.showShort(getApplicationContext(), "转发失败");
				}
			}
		}

	};
	
	protected void requestHttpSendStatus() {
		HttpRestClient.doHttpActionForImage(getIntent().getStringExtra("picID"), SmartFoxClient.getLoginUserId(),String.valueOf(0) , new AsyncHttpResponseHandler(this){
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				onBackPressed();
			}
		});
	}
	
	private ChatUserHelper chatUserHelper;
	
	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.salon_others);
		initWidget();
		initData();
	}

	private void initWidget() {
		initTitle();
		titleTextV.setText("搜索列表");
		entities = new ArrayList<GroupInfoEntity>();
		titleLeftBtn.setOnClickListener(this);
		pullRefreshView = (PullToRefreshListView) findViewById(R.id.hall);
		mListView = pullRefreshView.getRefreshableView();
		mSalonAdapter = new SearchAdapter<GroupInfoEntity>(this, entities);
		mListView.setAdapter(mSalonAdapter);
		mSalonAdapter.setonClickSalonAttentionListener(this);
		pullRefreshView.setOnRefreshListener(this);
		mAppData = HTalkApplication.getAppData();
		chatUserHelper = ChatUserHelper.getInstance();
		
		//从兴趣墙过来的
		if(getIntent().hasExtra("picID")){
			titleRightBtn2.setVisibility(View.VISIBLE);
			titleRightBtn2.setOnClickListener(this);
			titleRightBtn2.setText("确定");
			mSalonAdapter.setChangeMode(true);
		}else{
			mListView.setOnItemClickListener(this);
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		IntentFilter filter=new IntentFilter();
		filter.addAction(MessagePushService.ACTION_COLLECT_GROUP);
		filter.addAction(MessagePushService.ACTION_COLLECT_GROUP_NOT);
		filter.addAction(MessagePushService.ACTION_REPEAT_STATE);
		registerReceiver(receiver, filter);
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		unregisterReceiver(receiver);
	}
	
	private void initData() {
		mGroupInfoEntity = (GroupInfoEntity) getIntent().getExtras().get("mGroupInfoEntity");
		Flag = "";
		flagPlacing = "-100000";
		mGroupInfoEntity.setFlag(Flag);
		mGroupInfoEntity.setFlagPlacing(flagPlacing);
		mGroupInfoEntity.setPagesize(1);
		mGroupInfoEntity.setType(1);
		mGroupInfoEntity.setCreateCustomerID(SmartFoxClient.getLoginUserId());
		pullRefreshView.setRefreshing();
		SalonHttpUtil.getSalonInfoData(mGroupInfoEntity, 0,responseHandler);
	}
	
	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		Flag = "";
		flagPlacing = "-100000";
		mGroupInfoEntity.setFlag(Flag);
		mGroupInfoEntity.setFlagPlacing(flagPlacing);
		SalonHttpUtil.getSalonInfoData(mGroupInfoEntity, 0,responseHandler);
	}


	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
		mGroupInfoEntity.setFlag(Flag);
		mGroupInfoEntity.setFlagPlacing(flagPlacing);
		SalonHttpUtil.getSalonInfoData(mGroupInfoEntity, 0,responseHandler);
	}
	
	@Override
	public void onTicketHandler(String state, GroupInfoEntity entity) {
		if ("0".equals(state)) {
		} else if ("-1".equals(state)) {
		} else {
			Intent intent1 = new Intent();
			intent1.putExtra(ChatActivity.KEY_PARAME, entity);
			intent1.setClass(getApplicationContext(), ChatActivity.class);
			startActivity(intent1);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		try {
			SalonHttpUtil.onItemClick(this, this,getSupportFragmentManager(), entities.get(position - 1),true);
		} catch (Exception e) {
		}
	}

	@Override
	public void onClick(View v) {
		if (v.getTag() != null && v.getTag() instanceof Integer) {
			int position = (Integer) v.getTag();
			String id = entities.get(position).getCreateCustomerID();
			Intent intent = new Intent();
			if (id.equals(SmartFoxClient.getLoginUserId())) {
				intent.setClass(getApplicationContext(), SalonReadSelf.class);
			} else {
				intent.setClass(getApplicationContext(),SalonInformationActivity.class);
			}
			Bundle bundle = new Bundle();
			intent.putExtra("id", entities.get(position).getId());
			intent.putExtras(bundle);
			startActivity(intent);
		}else {
			switch (v.getId()) {
			case R.id.title_back:
				onBackPressed();
				break;
			case R.id.title_right2:
				SmartFoxClient.sendRepeatToFriend(String.valueOf(2),mSalonAdapter.getCusIds(),String.valueOf(getIntent().getStringExtra("picID")) );
				break;
			}
		}
		
	}

	
   private ResponseHandler responseHandler=new ResponseHandler();
	
	class ResponseHandler extends ObjectHttpResponseHandler{
		
		public void onFinish() {
			super.onFinish();
			pullRefreshView.onRefreshComplete();
		};
		
		@Override
		public void onSuccess(Object response) {
			super.onSuccess(response);
			if(response==null)return;
			if (flagPlacing.equals("-100000")) {
				entities.clear();
			}
			 ArrayList<GroupInfoEntity> newEntities=(ArrayList<GroupInfoEntity>) response;
			 if(newEntities.size()==0){
				 ToastUtil.showToastPanl("暂无更多内容...");
				 return;
			 }
			 	entities.addAll(newEntities);
				mSalonAdapter.notifyDataSetChanged();
				Flag = mSalonAdapter.getPageFlagMark(false,GroupInfoEntity.class);
				flagPlacing = mSalonAdapter.getFlagPlacingMark(false,GroupInfoEntity.class);
				if (flagPlacing.equals("-100000")) {
					mListView.setSelection(0);
				}
		}
		
		@Override
		public Object onParseResponse(String content) {
			if (!content.equals("N")) {
				return  SalonHttpUtil.jsonAnalysisSalonEntity(MySalonSearchActivity.this,content);
			}else {
				return null;
			}
		}
	}
	private GroupInfoEntity cacheGroupInfoEntity;
	private AppData mAppData;
	@Override
	public void onSalonAttentionClick(View v, GroupInfoEntity mSalonName,
			int positon) {
		cacheGroupInfoEntity = SalonHttpUtil.requestAttOrUnfollowToSalon(this,mSalonName);
	}
}
